<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px"
             v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="12" class="mb20">
          <el-form-item label="社保卡号" prop="medicalCard">
            <el-input v-model="form.medicalCard" placeholder="请输入社保卡号">
              <template #append v-if="!form.id">
                <el-button type="primary" @click="readCard">读卡</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="身份证号" prop="icCard">
            <el-input v-model="form.icCard" placeholder="请输入身份证号" @input="inputIcCard"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名"/>
          </el-form-item>
        </el-col>

        				<el-col :span="12" class="mb20">
        					<el-form-item label="出生日期" prop="birthday">
        						<el-date-picker type="date" placeholder="请选择出生日期" v-model="form.birthday"
        							:value-format="dateStr"></el-date-picker>
        					</el-form-item>
        				</el-col>

        				<el-col :span="12" class="mb20">
        					<el-form-item label="年龄" prop="age">
        						<el-input-number v-model="form.age" placeholder="请输入年龄"></el-input-number>
        					</el-form-item>
        				</el-col>

        				<el-col :span="12" class="mb20">
        					<el-form-item label="性别" prop="sex">
        						<el-radio-group v-model="form.sex">
        							<el-radio-button :label="item.value" v-for="(item, index) in gender" border :key="index">{{
        		item.label }}
        							</el-radio-button>
        						</el-radio-group>
        					</el-form-item>
        				</el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="form.tel" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="地址" prop="address">
            <el-input type="textarea" v-model="form.address" placeholder="请输入地址"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="卡号" prop="localCard">
            <el-input v-model="form.localCard" placeholder="请输入卡号"/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <!--          <el-form-item label="村" prop="village">-->
          <!--            <el-input v-model="form.village" placeholder="请输入村"/>-->
          <!--          </el-form-item>-->

          <el-form-item label="村" prop="village">
            <el-select v-model="form.village" placeholder="请输入村" @change="handleChangeVillage">
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in village"
                         :key="index"/>
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="12" class="mb20">
          <el-form-item label="家庭医生" prop="familyDoctor">
            <el-select v-model="form.familyDoctor" placeholder="请输入家庭医生" disabled>
              <el-option :key="item.userId" :label="item.name" :value="item.userId"
                         v-for="item in doctorList"/>
              <!--              <el-option :label="item.label" :value="item.value" v-for="(item, index) in family_doctor" :key="index" />-->
            </el-select>
            <!--						{{ form.doctorName }}-->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="管理状态" prop="healthStatus">
            <el-radio-group v-model="form.healthStatus">
              <el-radio-button :label="item.value" v-for="(item, index) in bloodx_health" border :key="index">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12" class="mb20">-->
        <!--          <el-form-item label="次数" prop="examNum">-->
        <!--            <el-input v-model="form.examNum" placeholder="请输入次数"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
    </el-form>

    <template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="BloodxCustomerDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from '/@/hooks/message';
import {getObj, addObj, putObj, sysVillageList} from '/@/api/blood/bloodxCustomer';
import {rule} from '/@/utils/validate';
import {readCardDevice} from '/@/utils/ajaxUtil';
import {getDoctorList} from "/@/api/information/village";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const village = ref([]);
const readCardWs = ref(null);
// 定义字典
const {gender, bloodx_health, family_doctor} = useDict('gender', 'bloodx_health', 'family_doctor');

const doctorList = ref<any[]>([]);
// 提交表单数据
const form = reactive({
  id: '',
  name: '',
  birthday: '',
  age: null,
  sex: '',
  examNum: '',
  icCard: '',
  tel: '',
  address: '',
  village: '',
  localCard: '',
  doctorName: '',
  medicalCard: '',
  healthStatus: '0',
  familyDoctor: '',
});

// 定义校验规则
const dataRules = ref({
  name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
  age: [{validator: rule.number, trigger: 'blur'}],
  // tel: [{ validator: rule.mobilePhone, trigger: 'blur' }],
  // village: [{ required: true, message: '请选择村', trigger: 'blur' }],
});

// 读卡
const readCard = async () => {
  loading.value = true;
  try {
    sendReadCard("ws://127.0.0.1:2018", (message) => {
      if (JSON.parse(message).Data.IsSuccess === false) {
        useMessage().error(JSON.parse(message).Data.msg)
        return;
      }
      useMessage().success('读卡成功');
      let list = JSON.parse(message).Data.kh.split("|")
      // console.log(list);
      form.name = list[4]
      form.medicalCard = list[2]
      form.icCard = list[1]
      form.localCard = list[2]
    });
    // const readRes = await sendReadCard();
    // if (readRes.code == 0) {
    // 	useMessage().success(readRes.msg);
    // 	form.name = '张三';
    // 	form.birthday = '1990-01-01';
    // 	form.age = 30;
    // 	form.medicalCard = readRes.data;
    // }
  } finally {
    loading.value = false;
  }
};

const sendReadCard = (WSURL: any, callback: any) => {
  if (readCardWs.value !== null) {
    if (
        readCardWs.value.readyState === 0 ||
        readCardWs.value.readyState === 1
    ) {
      return;
    } else {
      readCardWs.value.close();
    }
  }
  readCardWs.value = new WebSocket(WSURL);
  readCardWs.value.addEventListener("open", () => {
    readCardWs.value.send("读卡");
  });

  readCardWs.value.addEventListener("close", () => {
  });

  readCardWs.value.addEventListener("error", () => {
    readCardWs.value.close();
    useMessage().error('读卡失败');
  });

  readCardWs.value.addEventListener("message", (message) => {
    if (message.data !== "Open!") {
      readCardWs.value.close();
      callback(message.data);
    }

  });
}
const handleChangeVillage = (id: Object) => {
  console.log(village.value)
  form.familyDoctor = village.value.find((item) => item.id === id).doctorId;
  form.doctorName = village.value.find((item) => item.id === id).doctorName;
};

const inputIcCard = (val: string) => {
  if (val.length === 18) {
    form.birthday = val.substring(6, 10) + '-' + val.substring(10, 12) + '-' + val.substring(12, 14);
    form.sex = parseInt(val.substring(16, 17)) % 2 === 0 ? '2' : '1';
    form.age = new Date().getFullYear() - parseInt(val.substring(6, 10));
  }
};

const getdoctorList = () => {
  getDoctorList().then((res) => {
    doctorList.value = res.data;
  });
};

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true;
  form.id = '';
  sysVillageList().then((res) => {
    village.value = res.data;
  });
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取bloodxCustomer信息
  if (id) {
    form.id = id;
    getbloodxCustomerData(id);
  }

  getdoctorList();
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    if (form.birthday && form.birthday.indexOf(':') === -1) {
      form.birthday += ' 00:00:00';
    }
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getbloodxCustomerData = (id: string) => {
  // 获取数据
  loading.value = true;
  getObj(id)
      .then((res: any) => {
        Object.assign(form, res.data);
      })
      .finally(() => {
        loading.value = false;
      });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped>
.radius {
  border: 1px solid var(--el-border-color);
  margin-top: 20px;
  border-radius: 4px;
}

.el-input-group__append button.el-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary);
  color: var(--el-color-white);
}
</style>
